#include "compi/serializer.h"

#include <gtest/gtest.h>

#include <string>
#include <vector>

using namespace compi;

class SerializerStreamTest : public ::testing::Test
{
protected:
    void SetUp() override {}
    void TearDown() override {}
};

TEST_F(SerializerStreamTest, StreamBasicInt)
{
    serialization::vector_writer writer;
    int value = 123456;
    auto opts = make_serializer_options();
    serialization::serialize_stream(writer, value, opts);

    // 验证头部魔数 SRLZ
    const auto & data = writer.data();
    ASSERT_GE(data.size(), 4u);
    const std::string prefix(reinterpret_cast<const char *>(data.data()), 4);
    EXPECT_EQ(prefix, std::string("SRLZ"));

    // 读取
    std::vector<std::byte> buf(data.begin(), data.end());
    serialization::span_reader reader(kp::span<const std::byte>(buf.data(), buf.size()));
    int roundtrip = serialization::deserialize_stream<int>(reader, opts);
    EXPECT_EQ(roundtrip, value);
}

TEST_F(SerializerStreamTest, StreamVectorString)
{
    std::vector<std::string> original = {"alpha", "beta", "gamma", "delta"};
    serialization::vector_writer writer;
    auto opts = make_serializer_options();
    serialization::serialize_stream(writer, original, opts);

    const auto & data = writer.data();
    ASSERT_GE(data.size(), 4u);
    const std::string prefix(reinterpret_cast<const char *>(data.data()), 4);
    EXPECT_EQ(prefix, std::string("SRLZ"));

    std::vector<std::byte> buf(data.begin(), data.end());
    serialization::span_reader reader(kp::span<const std::byte>(buf.data(), buf.size()));
    auto roundtrip = serialization::deserialize_stream<std::vector<std::string>>(reader, opts);
    EXPECT_EQ(roundtrip, original);
}

TEST_F(SerializerStreamTest, StreamPair)
{
    std::pair<int, std::string> original{7, "seven"};
    serialization::vector_writer writer;
    auto opts = make_serializer_options();
    serialization::serialize_stream(writer, original, opts);

    const auto & data = writer.data();
    ASSERT_GE(data.size(), 4u);
    const std::string prefix(reinterpret_cast<const char *>(data.data()), 4);
    EXPECT_EQ(prefix, std::string("SRLZ"));

    std::vector<std::byte> buf(data.begin(), data.end());
    serialization::span_reader reader(kp::span<const std::byte>(buf.data(), buf.size()));
    auto roundtrip = serialization::deserialize_stream<std::pair<int, std::string>>(reader, opts);
    EXPECT_EQ(roundtrip.first, original.first);
    EXPECT_EQ(roundtrip.second, original.second);
}